// 主要功能已内联到layout.html中
// 此文件在完全内联模式下不会被使用

// Socket.io connection for real-time updates
let socket;

document.addEventListener('DOMContentLoaded', function () {
    // Initialize Socket.io connection if available
    if (typeof io !== 'undefined') {
        socket = io();

        socket.on('connect', function () {
            console.log('WebSocket connected');
        });

        socket.on('log_update', function (data) {
            appendLog(data.log, data.level);
        });

        socket.on('analysis_complete', function (data) {
            showNotification(`股票 ${data.stock_code} 分析完成`);

            // Refresh the page if we're on the relevant stock page
            const currentPath = window.location.pathname;
            if (currentPath === `/stock/${data.stock_code}` || currentPath === '/stocks') {
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            }
        });

        // Request initial logs if on logs page
        if (window.location.pathname === '/logs') {
            socket.emit('request_logs');

            socket.on('initial_logs', function (data) {
                const logContainer = document.getElementById('log-container');
                if (logContainer) {
                    logContainer.innerHTML = '';
                    data.logs.forEach(log => {
                        appendLog(log);
                    });
                }
            });
        }
    }

    // Initialize tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.forEach(function (tooltipTriggerEl) {
        new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Initialize any charts if the container exists
    const chartContainer = document.getElementById('stock-chart');
    if (chartContainer && window.chartData) {
        initializeStockChart(chartContainer, window.chartData);
    }

    // Add click handler for analysis buttons
    const analyzeButtons = document.querySelectorAll('.btn-analyze');
    analyzeButtons.forEach(button => {
        button.addEventListener('click', function () {
            const stockCode = this.getAttribute('data-stock');
            const analyzerType = this.getAttribute('data-analyzer') || null;

            if (stockCode) {
                startAnalysis(stockCode, analyzerType);
                this.disabled = true;
                this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 分析中...';
            }
        });
    });
});

function showNotification(message) {
    // Create notification element if it doesn't exist
    let notificationContainer = document.getElementById('notification-container');

    if (!notificationContainer) {
        notificationContainer = document.createElement('div');
        notificationContainer.id = 'notification-container';
        notificationContainer.style.position = 'fixed';
        notificationContainer.style.top = '20px';
        notificationContainer.style.right = '20px';
        notificationContainer.style.zIndex = '9999';
        document.body.appendChild(notificationContainer);
    }

    // Create the notification
    const notification = document.createElement('div');
    notification.className = 'toast';
    notification.setAttribute('role', 'alert');
    notification.setAttribute('aria-live', 'assertive');
    notification.setAttribute('aria-atomic', 'true');

    notification.innerHTML = `
        <div class="toast-header">
            <strong class="me-auto">系统通知</strong>
            <small>${new Date().toLocaleTimeString()}</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body">
            ${message}
        </div>
    `;

    notificationContainer.appendChild(notification);

    // Initialize and show the toast
    const toast = new bootstrap.Toast(notification, {
        autohide: true,
        delay: 5000
    });
    toast.show();

    // Remove the notification after it's hidden
    notification.addEventListener('hidden.bs.toast', function () {
        notification.remove();
    });
}

function appendLog(log, level) {
    const logContainer = document.getElementById('log-container');
    if (!logContainer) return;

    const logLine = document.createElement('div');

    // Add appropriate class based on log level
    if (level) {
        logLine.className = `log-${level.toLowerCase()}`;
    }

    // Format the log message
    logLine.textContent = log;

    // Add to container
    logContainer.appendChild(logLine);

    // Auto-scroll to bottom
    logContainer.scrollTop = logContainer.scrollHeight;
}

function initializeStockChart(container, data) {
    // Create an array of dates for the x-axis
    const dates = data.map(item => item.date);

    // Create arrays for OHLC data
    const opens = data.map(item => item.open);
    const highs = data.map(item => item.high);
    const lows = data.map(item => item.low);
    const closes = data.map(item => item.close);
    const volumes = data.map(item => item.volume);

    // Create candlestick chart
    const ctx = container.getContext('2d');
    const stockChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: dates,
            datasets: [
                {
                    label: '收盘价',
                    data: closes,
                    borderColor: 'rgba(54, 162, 235, 1)',
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderWidth: 2,
                    fill: false,
                    tension: 0.1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '日期'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '价格'
                    }
                }
            },
            plugins: {
                tooltip: {
                    callbacks: {
                        label: function (context) {
                            const index = context.dataIndex;
                            return [
                                `开盘: ${opens[index]}`,
                                `最高: ${highs[index]}`,
                                `最低: ${lows[index]}`,
                                `收盘: ${closes[index]}`,
                                `成交量: ${volumes[index]}`
                            ];
                        }
                    }
                }
            }
        }
    });
}

function startAnalysis(stockCode, analyzerType) {
    // Call the API to start analysis
    fetch('/api/analyze', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            stock_code: stockCode,
            analyzer_type: analyzerType
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                showNotification(`开始分析股票 ${stockCode}`);
            } else {
                showNotification(`分析请求失败: ${data.error}`);

                // Reset analyze buttons
                const buttons = document.querySelectorAll(`.btn-analyze[data-stock="${stockCode}"]`);
                buttons.forEach(button => {
                    button.disabled = false;
                    button.innerHTML = '分析';
                });
            }
        })
        .catch(error => {
            showNotification(`分析请求错误: ${error}`);

            // Reset analyze buttons
            const buttons = document.querySelectorAll(`.btn-analyze[data-stock="${stockCode}"]`);
            buttons.forEach(button => {
                button.disabled = false;
                button.innerHTML = '分析';
            });
        });
} 